package run.iget.framework.captcha.service.impl;

import java.util.Objects;

import org.springframework.stereotype.Service;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import run.iget.framework.cache.CacheUtils;
import run.iget.framework.captcha.req.CaptchaReq;
import run.iget.framework.captcha.resp.CaptchaResp;
import run.iget.framework.captcha.service.CaptchaService;
import run.iget.framework.common.enums.BaseResultEnum;
import run.iget.framework.common.util.ExceptionThrowUtils;

@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Override
    public CaptchaResp generate(Integer timeoutSeconds) {
        // 生成base64验证码
        SpecCaptcha captcha = new SpecCaptcha(150, 40);
        captcha.setLen(5);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        String text = captcha.text();
        // 生成key
        String key = IdUtil.fastSimpleUUID();
        // 封装返回数据
        CaptchaResp resp = new CaptchaResp();
        resp.setKey(key);
        resp.setImage(captcha.toBase64());

        log.info("key: {}, captcha: {}", key, text);
        int tSeconds = 10 * 60;
        if (Objects.nonNull(timeoutSeconds)) {
            tSeconds = timeoutSeconds;
        }
        CacheUtils.set(resp.getKey(), text, tSeconds);
        return resp;
    }

    @Override
    public void verify(CaptchaReq captchaReq) {
        String key = captchaReq.getKey();
        ExceptionThrowUtils.ofTrue(StrUtil.hasBlank(key, captchaReq.getCaptcha()), BaseResultEnum.ERROR_CAPTCHA);

        String cache = (String) CacheUtils.get(captchaReq.getKey());
        ExceptionThrowUtils.ofTrue(!StrUtil.equals(cache, captchaReq.getCaptcha(), true), BaseResultEnum.ERROR_CAPTCHA);
        CacheUtils.remove(captchaReq.getKey());
    }

}
